﻿using System.CodeDom;
using System.CodeDom.Compiler;
using System.ComponentModel.Design.Serialization;

namespace NetJsWire.Design.CodeDom
{
    internal class PrimitiveCodeDomSerializer : CodeDomSerializer
    {
        // Fields
        private static PrimitiveCodeDomSerializer _defaultSerializer;
        private static readonly string JSharpFileExtension = ".jsl";

        // Methods
        public override object Serialize( IDesignerSerializationManager manager, object value )
        {
            CodeExpression expression = new CodePrimitiveExpression( value );
            if ( value == null )
            {
                return expression;
            }
            if ( ( ( value is bool ) || ( value is char ) ) || ( ( ( value is int ) || ( value is float ) ) || ( value is double ) ) )
            {
                CodeDomProvider service = manager.GetService( typeof( CodeDomProvider ) ) as CodeDomProvider;
                if ( ( service != null ) && string.Equals( service.FileExtension, JSharpFileExtension ) )
                {
                    ExpressionContext context = manager.Context[ typeof( ExpressionContext ) ] as ExpressionContext;
                    if ( ( context != null ) && ( context.ExpressionType == typeof( object ) ) )
                    {
                        expression = new CodeCastExpression( value.GetType(), expression );
                        expression.UserData.Add( "CastIsBoxing", true );
                    }
                }
                return expression;
            }
            if ( value is string )
            {
                string str = value as string;
                if ( ( str != null ) && ( str.Length > 200 ) )
                {
                    expression = base.SerializeToResourceExpression( manager, str );
                }
                return expression;
            }
            return new CodeCastExpression( new CodeTypeReference( value.GetType() ), expression );
        }

        // Properties
        internal static PrimitiveCodeDomSerializer Default
        {
            get
            {
                if ( _defaultSerializer == null )
                {
                    _defaultSerializer = new PrimitiveCodeDomSerializer();
                }
                return _defaultSerializer;
            }
        }
    }


}
